<?php


namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Forms\DiscountForm;
use App\Modules\Good\Models\Good;
use App\Modules\Good\Models\GoodsDiscount;
use App\Modules\Good\Models\GoodsDiscountScope;
use Illuminate\Http\Request;
use App\Modules\Shop\Shop;
use Illuminate\Support\Facades\Auth;
use App\Modules\User\Models\Admin;
use App\Modules\Package\Models\GoodPackage;

class DiscountController extends Controller
{
    /**
     * 搜索门店
     */
    public function searchShops(Request $request){
        
        $this->checkAuth('staff_discount', 'discount');
        $term = $request->input('term');
        $query = Shop::query();
        $query->where('status', 'open');
        if (!empty($term)) {
            $query->where('name', 'like', "%".$term."%");
        }

        // $query->where('is_photography', 0);//非婚纱门店

        if (isset($this->authUser->is_merchant_staff) && $this->authUser->is_merchant_staff == Admin::MERCHANT_AUTH) {
            $query->whereIn('id', json_decode($this->authUser->shop_id, true));
        }

        $re = $query
            ->get()
            ->pluck('name', 'id')
            ->all();

        $re[0] = '全部门店';
        return $re;
    }

    public function index(Request $request)
    {
        $this->checkAuth('staff_discount', 'discount');

        $title    = $request->input('title');
        $shopId   = $request->input('shop_id', '');
        $shopName = $shopId ? Shop::query()->where('id', $shopId)->first('name')->name : '全部门店';

        $query = GoodsDiscount::query()
            ->leftJoin('shops', 'shops.id', '=', 'goods_discounts.shop_id')
            ->orderBy('created_at', 'desc');

        if (isset($this->authUser->is_merchant_staff) && $this->authUser->is_merchant_staff == Admin::MERCHANT_AUTH) {
            $query->whereIn('goods_discounts.shop_id', json_decode($this->authUser->shop_id, true));
        }
        
        if ($title != '') {
            $query->where('goods_discounts.title', 'like', "%" . $title . "%");
        }

        if ($shopId) {
            $query->where('goods_discounts.shop_id', $shopId);
        }

        $data = $query
                ->select('goods_discounts.*', 'shops.name as shop_name')
                ->paginate(30);

        return view('goods_discount.index', compact('data','title', 'shopId', 'shopName'));
    }

    public function create()
    {
        $this->checkAuth('staff_discount-add','discount-add');
        $form = $this->form(DiscountForm::class, [
            'url' => route('admin.discount.store'),
            'method' => 'POST',
        ]);
        return view('goods_discount.form', compact('form'));
    }

    public function store()
    {
        $this->checkAuth('staff_discount-add', 'discount-add');
        $form = $this->form(DiscountForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        $data['limit'] *= 100;
        $data['ratio'] *= 100;
        $data['admin_id'] = Auth::user()->id;

        $discount = GoodsDiscount::query()
            ->create($data);
        if (!empty($data['link_id'])) {
            foreach ($data['link_id'] as $value) {
                GoodsDiscountScope::query()
                    ->create([
                        'type' => GoodPackage::class,
                        'link_id' => $value,
                        'goods_discount_id' => $discount->id
                    ]);
            }
        }
        if (!empty($data['link_id2'])) {
            foreach ($data['link_id2'] as $value) {
                GoodsDiscountScope::query()
                    ->create([
                        'type' => Good::class,
                        'link_id' => $value,
                        'goods_discount_id' => $discount->id
                    ]);
            }
        }

        // $discount = GoodsDiscount::query()
        //     ->create($data);
        // if (!empty($data['goods_id'])) {
        //     foreach ($data['goods_id'] as $value) {
        //         GoodsDiscountScope::query()
        //             ->create([
        //                 'goods_id' => $value,
        //                 'goods_discount_id' => $discount->id
        //             ]);
        //     }
        // }
        return redirect()->route('admin.discount.index');
    }

    public function edit(GoodsDiscount $discount)
    {
        $this->checkAuth('staff_discount-edit', 'discount-edit');

        $scope = GoodsDiscountScope::query()
            ->where('goods_discount_id', $discount->id)
            ->where('type', GoodPackage::class)
            ->get();
        $discount->link_id = $scope->pluck('link_id');
        $package = GoodPackage::query()->find($scope->pluck('link_id'));

        $scope2 = GoodsDiscountScope::query()
            ->where('goods_discount_id', $discount->id)
            ->where('type', Good::class)
            ->get();
        $discount->link_id2 = $scope2->pluck('link_id');
        $goods = Good::query()->find($scope2->pluck('link_id'));

        // $scope = GoodsDiscountScope::query()
        //     ->where('goods_discount_id', $discount->id)
        //     ->get();
        // $discount->goods_id = $scope->pluck('goods_id');
        // $goods = Good::query()->find($scope->pluck('goods_id'));
        $discount->limit /= 100;
        $discount->ratio /= 100;

        // 获取门店
        $shops = Shop::query()->get(['id', 'name']);

        $form = $this->form(DiscountForm::class, [
            'url' => route('admin.discount.update', ['discount' => $discount]),
            'method' => 'PUT',
            'model' => $discount
        ], [
            'package' => $package->pluck('name', 'id')->all(),
            'goods' => $goods->pluck('name', 'id')->all(),
            'shops' => $shops->pluck('name', 'id')->all()
        ]);
        return view('goods_discount.form', compact('form'));
    }

    public function update(GoodsDiscount $discount)
    {
        $this->checkAuth('staff_discount-edit', 'discount-edit');

        $form = $this->form(DiscountForm::class);
        if (!$form->isValid()) {
            return redirect()->back()->withErrors($form->getErrors())->withInput();
        }
        $data = $form->getFieldValues();
        $old = GoodsDiscountScope::query()
            ->where('goods_discount_id', $discount->id)
            ->get()
            ->groupBy('type');
        $packageOld = $old->get(GoodPackage::class, collect())->pluck('link_id')->all();
        $data['link_id'] = $data['link_id']??[];
        $data['link_id'] = array_map('intval', $data['link_id']);
        $addPkg = array_diff($data['link_id'], $packageOld);
        $delPkg = array_diff($packageOld, $data['link_id']);
        foreach ($addPkg as $v_pkg) {
            GoodsDiscountScope::query()
                ->create([
                    'type' => GoodPackage::class,
                    'link_id' => $v_pkg,
                    'goods_discount_id' => $discount->id,
                ]);
        }
        foreach ($delPkg as $v_pkg) {
            GoodsDiscountScope::query()
                ->where('type', GoodPackage::class)
                ->where('link_id', $v_pkg)
                ->where('goods_discount_id', $discount->id)
                ->delete();
        }
        $goodsOld = $old->get(Good::class, collect())->pluck('link_id')->all();
        $data['link_id2'] = $data['link_id2']??[];
        $data['link_id2 '] = array_map('intval', $data['link_id2']);
        $addGoods = array_diff($data['link_id2'], $goodsOld);
        $delGoods = array_diff($goodsOld, $data['link_id2']);
        foreach ($addGoods as $v_goods) {
            GoodsDiscountScope::query()
                ->create([
                    'type' => Good::class,
                    'link_id' => $v_goods,
                    'goods_discount_id' => $discount->id,
                ]);
        }
        foreach ($delGoods as $v_goods) {
            GoodsDiscountScope::query()
                ->where('type', Good::class)
                ->where('link_id', $v_goods)
                ->where('goods_discount_id', $discount->id)
                ->delete();
        }
        unset($data['link_id']);
        unset($data['link_id2']);
        $data['limit'] *= 100;
        $data['ratio'] *= 100;
        $data['admin_id'] = Auth::user()->id;
        $discount->update($data);
        return redirect()->route('admin.discount.index');
    }


    public function destroy(GoodsDiscount $discount)
    {
        $this->checkAuth('staff_discount-delete', 'discount-delete');
        $discount->delete();
        GoodsDiscountScope::query()
            ->where('goods_discount_id', $discount->id)
            ->delete();
        return redirect()->route('admin.discount.index');
    }

    public function searchGoods(Request $request)
    {
        $search = $request->input('term');
        $shop_id = $request->input('shop_id');
        $query = Good::query()
            ->where('status', Good::STATUE_ON)
            ->whereNotExists(function ($query) {
                return $query->selectRaw('1')
                    ->from('goods_discount_scopes')
                    ->whereColumn("goods_discount_scopes.goods_id", '=', 'goods.id');
            })
            ->limit(500);
        if (!empty($search)) {
            $query->where('name', "like", "%".$search."%");
        }
        if (!empty($shop_id)) {
            $query->where('shop_id', $shop_id);
        }
        $re = $query->get()
            ->pluck('name', 'id');
        return $re;
    }
}
